<template>
  <div class="app-container">
    <!-- 骨架屏 -->
    <mobile-skeleton 
      v-if="loading" 
      :showHeader="true"
      :showSearch="false"
      :showCards="false"
      :showTable="false"
      :showForm="true"
      :formFields="3"
      :showPagination="false"
    />
    
    <template v-else>
      <el-row :gutter="24">
        <el-col :span="24" style="margin-bottom: 20px" v-loading="loading">
          <el-alert title="学习完成后，点击`随堂测验`获取测验试题，测试通过方为完成本节内容学习" type="error" style="margin-bottom: 10px" />
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-button style="float: left; padding: 3px 0;margin-right:10px" type="text"><img :src="backImg"
                  style="width:25px;height:25px;cursor:pointer" @click="$router.go(-1)" /></el-button>
              <span v-if="data.category && data.category.name !== undefined" :style="{
                color: theme,
                padding: '5px 0',
                display: 'block',
                fontWeight: 'bold'
              }">{{ data.category.name }} ｜{{ data.name }}</span>
            </div>
            <div v-html="data.content" class="text item" @click="imageChagange($event)"></div>
            <ElImageViewer :on-close="closeViewer" v-if="showViewer" :url-list="srcListView" />

            <el-button type="primary" :style="[{ backgroundColor: disabled ? '#eee' : theme }, { border: 0 }]" size="small"
              @click="getExam()" :disabled="disabled" style="margin:20px 0;display:block;float:right;">随堂测验
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </template>
    
    <el-dialog title="随堂测试" :visible.sync="dialogVisible" width="60%" center v-loading='dialogLoading'>
      <!-- <el-alert type="warning" description="无考核内容" center v-show="questions.length == 0">
      </el-alert> -->

      <div v-loading="!(questions.length !== 0)" v-for="quData in questions" :key="quData.id" class="qu-content">
        <p v-html="quData.stem + '(单选题)'" style="font-weight:bold" v-show="quData.type == 1" class="paperData_title" />
        <p v-html="quData.stem + '(多选题)'" style="font-weight:bold" v-show="quData.type == 2" class="paperData_title" />
        <p v-html="quData.stem + '(判断题)'" style="font-weight:bold" v-show="quData.type == 3" class="paperData_title" />
        <p v-html="quData.stem + '(问答题)'" style="font-weight:bold" v-show="quData.type == 4" class="paperData_title" />

        <div v-show="quData.type == 1">
          <el-radio-group v-model="radioValue">
            <el-radio v-for="item in quData.option" :label="item.id" :key="item.id">{{ item.name }}.{{ item.content }}
              <div v-if="item.image != null && item.image != ''" style="clear: both">
                <el-image :src="item.image" style="max-width:100%;" />
              </div>
            </el-radio>
          </el-radio-group>
        </div>
        <!-- 多选题 -->
        <div v-show="quData.type == 2">
          <el-checkbox-group v-model="multiValue">
            <el-checkbox v-for="item in quData.option" :label="item.id" :key="item.id">{{ item.name }}.{{ item.content }}
              <div v-if="item.image != null && item.image != ''" style="clear: both">
                <el-image :src="item.image" style="max-width:100%;" />
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <!-- 判断题 -->
        <div v-show="quData.type == 3">
          <el-radio-group v-model="radioValue">
            <el-radio label="1">对 </el-radio>
            <el-radio label="0">错 </el-radio>
          </el-radio-group>
        </div>
        <!-- 问答题 -->
        <div v-show="quData.type == 4">
          <el-input type="textarea" v-model="questionValue" placeholder="请填写答案"></el-input>
        </div>
      </div>

      <div v-show="resultShow">
        <el-row :gutter="10" v-show="result.is_right">
          <el-col :span="24">
            <p :style="{
              color: theme,
              padding: '5px 0',
              display: 'block',
              fontWeight: 'bold'
            }">
              回答正确，恭喜通过本小节测试！
            </p>
            <!-- <p>答案解析：{{result.explain}}</p> -->
          </el-col>
        </el-row>
        <el-row :gutter="10" v-show="!result.is_right">
          <el-col :span="24">
            <p style="color:red">回答错误，请返回继续学习！</p>
            <p :style="{
              color: theme,
              padding: '5px 0',
              display: 'block',
              fontWeight: 'bold'
            }">
              正确答案：
              <span v-for="item in result.right_answer" :key="item">{{
                item
              }}</span>
            </p>
            <p>答案解析：{{ result.explain }}</p>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialogVisible()">取 消</el-button>
        <el-button type="primary" @click="submitForm()" v-show="showBtn">确 定</el-button>
        <el-button type="primary" v-show="showCount" @click="handleChange();">{{ count
        }}秒后将自动跳转下一节进行学习</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import backImg from "@/assets/images/back.png";
import { mapGetters, mapState } from "vuex";
import { knowledgeDetailId } from "@/api/vadmin/course/course";
import { getTrainTest, postTrainTest, trainTestDetail, trainDetail } from "@/api/vadmin/train/train";
import variables from "@/assets/styles/variables.scss";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "newKnowledge",
  components: {
    ElImageViewer: () => import("element-ui/packages/image/src/image-viewer"),
    MobileSkeleton
  },
  data() {
    return {
      showViewer: false,
      srcListView: [],

      // 遮罩层
      loading: true,
      backImg: backImg,
      data: "",
      count: 5, //计时器
      countBtn: 5, //计时器
      disabled: true,//随堂测试按钮
      dialogVisible: false, //弹窗
      dialogLoading: true, //弹窗加载
      showBtn: true, //提交按钮
      showCount: false, //倒计时按钮
      timer: null, //定时器
      questions: [],
      radioValue: [],
      multiValue: [],
      questionValue: "",
      knowledgeId: "",
      form: {
        answer: null,
      },
      result: {},
      resultShow: false,
      previousPage: {},
      nextPage: {},
      cur_id: null,
      next_id: null,
      chapterList: [],
      trainId: '',
      isSupplementMode: false, // 标记是否为补学模式
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },

  created() {
    console.log(2222, this.$route.params)
    if (this.$route.params.id) {
      this.trainId = this.$route.params.id
      this.initTrainDetails()
    } else {
      this.trainId = sessionStorage.getItem("trainId")
      this.initTrainDetails()
      // this.getList();
    }
  },
  mounted() { },

  methods: {
    initTrainDetails() {
      this.loading = true
      this.cur_id = ''
      this.isSupplementMode = false // 初始化时重置补学模式
      this.getTrainDetails()
    },
    getList(id) {//获取当前培训知识点详情
      this.loading = true;
      this.disabled = true
      this.countBtn = 5
      knowledgeDetailId(id).then((res) => {
        // console.log("当前知识点详情", res)
        this.data = res;
        this.knowledgeId = res.id;
        this.loading = false;
        this.timer2 = setInterval(() => {
          this.countBtn--; //递减
          if (this.countBtn <= 0) {
            this.disabled = false
            clearInterval(this.timer2);
          }
        }, 1000)
      });
    },
    getTrainDetails() {//获取当前培训知识点id s
      this.loading = true
      this.cur_id = ''
      trainDetail(this.trainId).then(res => {
        console.log("培训页详情", res)

        // 首先检查 _Knowledge.next 是否有值（正常的学习流程）
        if (res._Knowledge && res._Knowledge.next !== null && res._Knowledge.next !== '') {
          this.cur_id = res._Knowledge.next
          this.getList(this.cur_id)
        } else {
          // 如果 _Knowledge.next 为空，检查 Knowledge 数组中是否还有未完成的项目
          const unfinishedKnowledge = this.findNextUnfinishedKnowledge(res.Knowledge)

          if (unfinishedKnowledge) {
            console.log("找到未完成的知识点:", unfinishedKnowledge)
            // 标记这是补学模式，避免无限循环
            this.isSupplementMode = true
            this.cur_id = unfinishedKnowledge.id
            this.getList(this.cur_id)
          } else {
            // 真正完成所有学习
            this.showCompletionDialog()
          }
        }

        clearInterval(this.timer);
        clearInterval(this.timer2);
        this.dialogVisible = false;
        this.showCount = false;
        this.loading = false
      }).catch((res => {
        console.error("获取培训详情失败:", res)
        this.loading = false
      }))
    },

    // 显示完成对话框
    showCompletionDialog() {
      this.$confirm("已完成本课程学习，点击'确定'返回上一步", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "返回",
        type: "success",
      })
        .then(() => {
          this.$router.push({ name: "train" });
        })
        .catch(() => {
          this.$router.go(-1)
        });
    },

    // 查找下一个未完成的知识点
    findNextUnfinishedKnowledge(knowledgeList) {
      if (!knowledgeList || !Array.isArray(knowledgeList)) {
        console.log("知识点列表无效");
        return null;
      }

      // 按 sort 字段排序，确保按顺序学习
      const sortedKnowledge = knowledgeList.sort((a, b) => a.sort - b.sort);

      // 查找第一个 is_passed 为 null 的知识点
      const unfinished = sortedKnowledge.find(item => item.is_passed === null);

      if (unfinished) {
        console.log("找到未完成的知识点:", unfinished.name, "ID:", unfinished.id);
      } else {
        console.log("所有知识点都已完成");
      }

      return unfinished;
    },


    //切换知识点
    handleChange() {
      clearInterval(this.timer);
      clearInterval(this.timer2);
      this.dialogVisible = false;
      this.show = false;

      // 如果是补学模式，需要特殊处理
      if (this.isSupplementMode) {
        this.handleSupplementModeNext();
      } else {
        // 正常模式，继续获取下一个知识点
        this.getTrainDetails();
      }
    },

    // 处理补学模式的下一步
    handleSupplementModeNext() {
      this.loading = true;
      trainDetail(this.trainId).then(res => {
        console.log("补学模式检查培训详情", res);

        // 在补学模式下，重新检查是否还有未完成的知识点
        const unfinishedKnowledge = this.findNextUnfinishedKnowledge(res.Knowledge);

        if (unfinishedKnowledge) {
          console.log("补学模式：找到下一个未完成的知识点:", unfinishedKnowledge);
          this.cur_id = unfinishedKnowledge.id;
          this.getList(this.cur_id);
        } else {
          // 补学模式下所有知识点都完成了
          console.log("补学模式：所有知识点已完成");
          this.isSupplementMode = false; // 退出补学模式
          this.showCompletionDialog();
        }

        this.loading = false;
      }).catch((error) => {
        console.error("补学模式获取培训详情失败:", error);
        this.loading = false;
        this.$message.error("获取培训信息失败，请重试");
      });
    },

    // 获取题
    getExam() {
      this.dialogVisible = true;
      this.resultShow = false;
      this.showBtn = true;
      this.showCount = false;
      this.dialogLoading = true
      getTrainTest({
        knowledge: this.knowledgeId
      }).then((res) => {
        this.reset();
        this.show = true;
        this.dialogLoading = false

        if (res && res.length > 0) {
          // /TrainTest/?knowledge=xxx 返回的数组只有一条数据
          this.questions = res;
          console.log("获取到的题目:", res);
        } else {
          this.questions = [];
          this.$message.info("当前知识点没有测验题目");
        }
      }).catch((error) => {
        console.error("获取题目失败:", error);
        this.$message.error("获取题目失败，请重试");
        this.dialogLoading = false;
        this.questions = [];
      });
    },
    // 重置答题表单
    reset() {
      this.radioValue = null;
      this.multiValue = [];
      this.questionValue = "";

      this.form = {
        id: "",
        answer: null,
        train: sessionStorage.getItem("trainId"),
      };
    },
    /** 提交按钮 */
    submitForm() {
      // 检查是否有题目
      if (!this.questions || this.questions.length === 0) {
        this.$message.warning('没有题目可以提交');
        this.showBtn = true;
        return;
      }

      // /TrainTest/?knowledge=xxx 返回的数组只有一条数据，直接使用 [0]
      const question = this.questions[0];
      const type = question.type;

      // 验证是否已答题
      if (type == 1 || type == 3) {
        // 单选题和判断题
        if (this.radioValue === null || this.radioValue === undefined || this.radioValue === '') {
          this.$message.warning('请选择答案后再提交');
          this.showBtn = true;
          return;
        }
      } else if (type == 2) {
        // 多选题
        if (!this.multiValue || this.multiValue.length === 0) {
          this.$message.warning('请选择答案后再提交');
          this.showBtn = true;
          return;
        }
      } else if (type == 4) {
        // 问答题
        if (!this.questionValue || this.questionValue.trim() === '') {
          this.$message.warning('请填写答案后再提交');
          this.showBtn = true;
          return;
        }
      }

      this.showBtn = false;

      // 格式化答案
      if (type == 1) {
        const cur_arr = [];
        cur_arr.push(this.radioValue);
        this.form.answer = JSON.stringify(cur_arr); //转换为列表字符串如："[arr]"
      } else if (type == 3) {
        this.form.answer = this.radioValue + ""; //判断题参数为字符串
      } else if (type == 2) {
        this.form.answer = JSON.stringify(this.multiValue.sort());
      } else if (type == 4) {
        this.form.answer = this.questionValue;
      }

      this.form.id = question.id;
      this.form.train = this.trainId;

      postTrainTest(this.form).then((res) => {
        this.result = res;

        // 处理正确答案显示
        if (question.type == 1 || question.type == 2) {
          question.option.map((item) => {
            for (let i in this.result.right_answer) {
              if (this.result.right_answer[i] == item.id) {
                this.result.right_answer[i] = item.name;
              }
            }
          });
        } else if (question.type == 3) {
          if (res.right_answer == 1) {
            this.result.right_answer = "对";
          } else {
            this.result.right_answer = "错";
          }
        }

        this.resultShow = true;
        if (this.result.is_right) {
          //定时器开始
          this.showCount = true;
          this.count = 5;
          this.timer = setInterval(() => {
            this.count--; //递减
            if (this.count <= 0) {
              this.dialogVisible = false;
              this.handleChange();
              this.showCount = false;
            }
          }, 1000); //1000毫秒后执行
        }

        // 重置表单
        this.form = {
          id: "",
          answer: null,
          train: this.$route.params.id || sessionStorage.getItem("trainId"),
        };
      }).catch((error) => {
        console.error("提交答案失败:", error);
        this.$message.error("提交失败，请重试");
        this.showBtn = true;
      });
    },
    // 弹窗关闭
    closeDialogVisible() {
      this.dialogVisible = false;
      clearInterval(this.timer);
      this.timer = null;
    },
    imageChange(e) {
      if (e.target.nodeName === "IMG" || e.target.nodeName == "img") {
        //判断是否图片标签
        const img = e.target.currentSrc; //获取点击图片地址
        this.onPreview(img);
      }
    },
    //开启富文本图片预览
    onPreview(img) {
      this.srcListView = [img];
      this.showViewer = true;
    },
    //关闭富文本渲染文本图片预览
    closeViewer() {
      this.showViewer = false;
    },

  },
};
</script>

<style lang="scss" scoped>
.switch_page {
  border-bottom: 1px solid #e6ebf5;
  padding: 5px 0;
}

/deep/ .el-dialog__title {
  color: rgb(255, 173, 69) !important;
  font-weight: bold;
}

/deep/ .el-dialog--center .el-dialog__body {
  padding-top: 0px !important;
}

/deep/ .el-dialog .el-dialog--center {
  margin-top: 25vh !important;
  width: 60%;
}

/deep/ .el-dialog:not(.is-fullscreen) {
  margin-top: 25vh !important;
}

.click_title {
  cursor: pointer;
}

.paperData_title {
  display: flex;
  align-items: center;
}

.el-checkbox {
  width: 100%;
  margin-bottom: 5px;
}
</style>